package com.jvm123.blog.service

import com.jvm123.blog.dao.TermRepos
import com.jvm123.blog.entity.Term
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

import java.util.function.Consumer

/**
 *
 * @author yawn http://jvm123.com
 *     2019/10/23 17:17
 */
@Service
class TermServiceImpl implements TermService {

    @Autowired
    TermRepos termRepos

    @Override
    List<Term> findCategories() {
        List<Term> terms = termRepos.findAllByTaxonomy("category")
        distinctTerms(terms)
    }

    @Override
    List<Term> findTags() {
        List<Term> terms = termRepos.findAllByTaxonomy("post_tag")
        distinctTerms(terms)
    }

    @Override
    List<Long> findPostIdByTag(String tag) {
        termRepos.findPostIdBySlugAndTaxonomy(tag, "post_tag")
    }

    @Override
    List<Long> findPostIdByCategory(String category) {
        termRepos.findPostIdBySlugAndTaxonomy(category, "category")
    }

    @Override
    Term findBySlug(String slug) {
        termRepos.findFirstBySlug(slug)
    }

    private static ArrayList<Term> distinctTerms(List<Term> terms) {
        List<Term> termList = []
        Jdk8Utils.OpDistinctElement(terms, new Consumer<Term>() {
            @Override
            void accept(Term term) {
                termList << term
            }
        })
        termList
    }
}
